import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from api_key import handler, get_api_key
import hmac
from api_key import handler as api_key_handler
from api_key import get_api_key_by_key,get_api_key
import hashlib
import logging
from api_key import handler as api
import urllib
def verify_api_sig(requst_url, secret_key, api_sig):
    """
        Verify the request
        
    """
    sig = hmac.new(secret_key,
                   msg = requst_url,
                   digestmod=hashlib.sha1).hexdigest()
    #TODO
    logging.info(sig)
    return api_sig == sig

def check_request(request):
    #0. Read neccessary parameters
    api_key = request.get('api_key')
    api_sig = request.get('api_sig')
    
    api = api_key.get_api_key(api_key)
    if not api or not api_sig:
        return None
    #1.sort parameter
        params = dict([x.split('=')
                       for x in request.query_string.split('&')])
        #lamda expression
        del params['api_sig']
    #2.remove api_sig()
        tmp = params.items()
        tmp.sort()
    #3.rebuild URL request
        query_string = '&'.join([k+'=' + urllib.quote(str(v))
                                 for (k,v) in tmp])
    #4. verify sinature.
        return verify_api_sig(request.path)
    return True

class HttpServices(webapp.RequestHandler):
    def common(self,handler,method):  #self con tro
        self.response.headers['Content-Type'] = 'application/json; charset = utf-8'
        if( not check_request(handler.request)):
            #failed
            self.response.out.write("dong maua anh hung")
        #continue
        self.response.out.write("bi carazy roi")
        
    def post(self):
        self.common(self,'POST')
    
    def get(self):
        self.common(self,'GET')


application = webapp.WSGIApplication([
        ('/api_key/add', api_key_handler.AddApiKey),
        ('bkitmobile/hello', HttpServices)
], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()